package com.ice.cloud.filter;


import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

import java.lang.runtime.ObjectMethods;
import java.util.HashMap;

// 全局过滤器
@Component   //注入sping容器里面
//GlobalFilter：Spring Cloud Gateway 的全局过滤器接口，实现它的类会对所有请求生效
// Ordered：用于指定过滤器的执行顺序
public class AuthFilter implements GlobalFilter, Ordered {


    //这是过滤器的核心方法，实现了具体的过滤逻辑
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        HttpHeaders headers = exchange.getRequest().getHeaders(); //通过ServerWebExchange获取请求头信息
        String token = headers.getFirst("token");  //从请求头中获取名为 "token" 的参数
        if(!"aaabbbccc".equals(token)){//简单验证 token 是否等于 "aaabbbccc"（实际项目中会是更复杂的验证逻辑）
            return  setUnauthorizedResponse(exchange,"token无效"); //如果 token 无效，调用setUnauthorizedResponse()返回错误响应
        }
        return  chain.filter(exchange);//如果 token 有效，调用chain.filter(exchange)继续执行过滤器链
    }


    //这个方法用于构建未授权的响应信息：
    private Mono<Void> setUnauthorizedResponse(ServerWebExchange exchange, String msg) {
        //获取响应对象并设置状态码为 401（未授权）
        ServerHttpResponse originalResponse = exchange.getResponse();
        originalResponse.setStatusCode(HttpStatus.UNAUTHORIZED);
        //设置响应头为 JSON 格式
        originalResponse.getHeaders().add("Content-Type", "application/json;charset=UTF-8");

        //构建包含错误代码和消息的响应体
        HashMap data = new HashMap();
        data.put("code",401);
        data.put("msg",msg);
        ObjectMapper objectMapper = new ObjectMapper();
        byte[] res = null;
        try {
            //使用 Jackson 的ObjectMapper将 Java 对象转换为 JSON 字符串
            res =objectMapper.writeValueAsString(data).getBytes();
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }

        //将 JSON 字符串转换为DataBuffer并写入响应
        DataBuffer buffer = originalResponse.bufferFactory().wrap(res);
        return originalResponse.writeWith(Flux.just(buffer));
    }

    //实现Ordered接口的方法，返回值越小，过滤器执行顺序越靠前。这里返回 1，表示该过滤器会在大部分过滤器之前执行。
    @Override
    public int getOrder() {
        return 1;
    }
}